import { request } from "../utils/request";

const key = "JWT_TOKEN";
const userKey = "USER";

export function getToken() {
  return localStorage.getItem(key);
}

export function setToken(val) {
  localStorage.setItem(key, val);
}
export function saveUserInfo(val) {
  localStorage.setItem(userKey, JSON.stringify(val));
}

export function getUserInfo() {
  return JSON.parse(localStorage.getItem(userKey));
}

export async function register(email, username, password) {
  const result = await request("/api/auth/local/register", {
    method: "POST",
    auth: false,
    body: {
      email,
      username,
      password,
      name: username,
    },
  });
  setToken(result.jwt);
  saveUserInfo(result.user);
  return result.user;
}

export async function login(email, password) {
  const result = await request("/api/auth/local", {
    method: "POST",
    auth: false,
    body: {
      identifier: email,
      password,
    },
  });
  setToken(result.jwt);
  saveUserInfo(result.user);
  return result.user;
}
